﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace Ymatou.ExcelConvert.Client
{
    public static class ExcelConvertClient
    {
        /// <summary>
        ///     调用 Excel Convert 服务转换 为 2003格式,并返回文件流
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static ActionResult ConvertExcelResult(this Controller controller, HttpPostedFileBase file, string fileDownloadNameWithoutExtension = null, string format = "xlexcel8")
        {
            Stream responseStream = Convert(file, format);
            string extension = GetExtension(format);
            string fileDownloadName = string.IsNullOrEmpty(fileDownloadNameWithoutExtension) ? Path.GetFileNameWithoutExtension(file.FileName) + extension : fileDownloadNameWithoutExtension + extension;
            return new FileStreamResult(responseStream, "application/ms-excel")
            {
                FileDownloadName = fileDownloadName
            };
        }

        public static ActionResult ConvertExcelResult(this Controller controller, string fileName, Stream file, string fileDownloadNameWithoutExtension = null, string format = "xlexcel8")
        {
            string extension = GetExtension(format);
            string fileDownloadName = string.IsNullOrEmpty(fileDownloadNameWithoutExtension) ? Path.GetFileNameWithoutExtension(fileName) + extension : fileDownloadNameWithoutExtension + extension;
            Stream responseStream = Convert(fileName, file, format);
            return new FileStreamResult(responseStream, "application/ms-excel")
            {
                FileDownloadName = fileDownloadName
            };
        }

        private static string GetExtension(string format)
        {
            string extension;
            switch (format.ToLower())
            {
                case "xlexcel8":
                    extension = ".xls";
                    break;
                case "xlexcel12":
                    extension = ".xlsx";
                    break;
                default:
                    throw new NotSupportedException();
                    break;
            }
            return extension;
        }

        public static ActionResult ConvertExcelResult(this Controller controller, string fileName, string fileDownloadNameWithoutExtension = null, string format = "xlexcel8")
        {
            var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            return ConvertExcelResult(controller, fileName, fileStream, fileDownloadNameWithoutExtension, format);
        }

        public static Stream Convert(HttpPostedFileBase file, string format)
        {
            Stream inputStream = file.InputStream;
            string fileName = file.FileName;
            return Convert(fileName, inputStream, format);
        }

        /// <summary>
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="inputStream"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static Stream Convert(string fileName, Stream inputStream, string format)
        {
            string savedFileName = Path.GetFileName(fileName);
            var bt = new byte[inputStream.Length];
            inputStream.Read(bt, 0, bt.Length);
            inputStream.Close();
            string api = GetExcelConvertServiceApiUrl(format);
            string bhkey = GetBHKey();
            string split = api.Contains("?") ? "&" : "?";
            string url = api + split + "fname=" + savedFileName + "&bhkey=" + bhkey;
            var req = (HttpWebRequest) WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            using (Stream requestStream = req.GetRequestStream())
            {
                requestStream.Write(bt, 0, bt.Length);
                requestStream.Close();
            }
            WebResponse response = req.GetResponse();
            Stream responseStream = response.GetResponseStream();
            return responseStream;
        }

        private static string GetBHKey()
        {
            string key = "bh051986943966";
            string apiSetting = ConfigurationManager.AppSettings["ExcelConvertServiceApiKey"];
            if (!string.IsNullOrEmpty(apiSetting))
            {
                key = apiSetting;
            }
            return key;
        }

        private static string GetExcelConvertServiceApiUrl(string format)
        {
            string api = "http://localhost:12132/File/ConverExcelFormat";
            string apiSetting = ConfigurationManager.AppSettings["ExcelConvertServiceApiUrl"];
            if (!string.IsNullOrEmpty(apiSetting))
            {
                api = apiSetting;
            }
            return api + "?format=" + format;
        }
    }
}